﻿using System;
using TouchSocket.Sockets;

namespace TK.TSocket
{
    /// <summary>
    /// 数据接收插件,Order = -1
    /// </summary>
    public class ReceiveDataPlug : TcpPluginBase<ISocketClient>
    {
        private readonly IReceiveData _receiveData;

        /// <summary>
        /// ctor
        /// </summary>
        public ReceiveDataPlug(IReceiveData receiveData)
        {
            Order = -1;
            _receiveData = receiveData;
        }

        #region base methods
        /// <summary>
        /// OnReceivedData
        /// </summary>
        protected override void OnReceivedData(ISocketClient client, ReceivedDataEventArgs e)
        {
            e.Handled = true;
            ReceiveDataHandle(client, e);
            base.OnReceivedData(client, e);
        }
        #endregion

        #region private methods
        /// <summary>
        /// 适配器后数据接收处理
        /// </summary>
        private void ReceiveDataHandle(ISocketClient client, ReceivedDataEventArgs e)
        {
            DataPacket dataPacket = new DataPacket
            {
                ServerIp = client.ServiceIP,
                ServerPort = client.ServicePort,
                ClientIp = client.IP,
                ClientPort = client.Port,
                ClientId = client.ID,
                DataType = DataType.Receive
            };
            if (e.RequestInfo != null)
            {
                dataPacket.RequestInfo = e.RequestInfo;
            }
            else
            {
                dataPacket.Data = new byte[e.ByteBlock.Len];
                e.ByteBlock.Read(dataPacket.Data, 0, e.ByteBlock.Len);
            }

            _receiveData.ReceiveDataAsync(dataPacket);
        }
        #endregion
    }
}
